package com.lingrit.provider.aop;

import com.alibaba.fastjson.JSON;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

/**
 * @author JuiceYan
 * @date 2018/04/11
 */
@Aspect
@Component
public class RequestLog {

    private Logger log = LoggerFactory.getLogger(RequestLog.class);

    @Pointcut("execution(* com.lingrit.provider.controller..*Controller.*(..))")
    public void request() {
    }

    @Around("request()")
    public Object recordSysLog(ProceedingJoinPoint point) throws Throwable {
        //先执行业务
        Object result = point.proceed();
        if (null != result) {
            log.info(JSON.toJSONString(result));
        }
        try {
            handle(point);
        } catch (Exception e) {
            log.error("日志记录出错!", e);
        }

        return result;
    }

    private void handle(ProceedingJoinPoint point) throws Exception {
        Signature methodName = point.getSignature();
        List<Optional<Object>> objects = Arrays.asList(Optional.ofNullable(point.getArgs()));
        objects.forEach(obj -> {
            obj.ifPresent(objValue -> {
                log.info(methodName + " " + JSON.toJSONString(objValue));
            });
        });
    }
}